package com.tdam2013.grupo04.networking;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class LiveConnectivityManager {

	/** Unique manager in application */
	private static LiveConnectivityManager mManager;
	private static List<ConnectivityObserver> mObservers;
	/**
	 * Implements singleton pattern
	 * 
	 * @param context
	 *            Execution context
	 * @return Connectivity Manager
	 */
	public static LiveConnectivityManager singleton(Context context) {
		if (mManager == null) {
			mManager = new LiveConnectivityManager(context);
		}
		return mManager;
	}

	private boolean mConnected;

	private final Context mContext;

	/** Class constructor */
	private LiveConnectivityManager(Context context) {
		mObservers = new ArrayList<ConnectivityObserver>();
		this.mContext = context;
		this.mConnected = this.isConnectionEnabled();
	}

	/** Adds observer to observers list */
	public void addObserver(ConnectivityObserver observer) {
		mObservers.add(observer);
		observer.manageNotification(this.mConnected);
	}

	/** Test if connection is enabled */
	boolean isConnectionEnabled() {
		try {
			ConnectivityManager cm = (ConnectivityManager) this.mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo netInfo = cm.getActiveNetworkInfo();
			return netInfo != null && netInfo.isConnectedOrConnecting();
		} catch (Exception e) {
			return false;
		}
	}

	/** Called when there's a connectivity change. */
	void notifyConnectionChange() {
		this.mConnected = this.isConnectionEnabled();
		for (ConnectivityObserver observer : mObservers) {
			observer.manageNotification(this.mConnected);
		}
	}

	/** Remove observer form observers list */
	public void removeObserver(ConnectivityObserver observer) {
		mObservers.remove(observer);
	}
}
